from flask import Blueprint, current_app, request

from packages.tools.base_tool import UrlWrapUtil
from packages.common.base import R
from packages.core.auth.decorators import HasPerm
from modules.sys.services.file_info_service import FileInfoService
from packages.common.base import IdForm, IdsForm
from packages.common.base_model import db
from modules.sys.validators.file_info_validator import FileInfoForm, FileInfoPageForm
from modules.sys.models.file_info import FileInfo
from packages.tools.base_tool import generate_id

# 声明一个蓝图
file_info = Blueprint('file_info', __name__, url_prefix="/sys/fileInfo")

# 声明一个文件信息业务服务
file_info_service = FileInfoService(db=db)


@file_info.route("/detail", methods=['POST'])
@HasPerm(access="sys:fileInfo:detail", name="通过id获取文件信息信息")
def file_info_detail():
    """
    通过id获取文件信息信息
    :return:
    """
    form = IdForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # 或者直接拿id值 id=form.id.data
    # u = FileInfo.query.filter_by(id=form.id.data).first()
    # 通过主键查询
    u = file_info_service.detail(form)
    if u is not None:
        return R.data(u.to_dict())
    else:
        return R.fail("该记录不存在")


@file_info.route("/page", methods=['POST'])
@HasPerm(access="sys:fileInfo:page", name="分页查询文件信息列表")
def file_info_page():
    """
    分页查询文件信息列表
    :return:
    """
    form = FileInfoPageForm()
    form.validate_for_api()
    return R.data(file_info_service.page(form))


@file_info.route("/save", methods=['POST'])
@HasPerm(access="sys:fileInfo:save", name="添加文件信息")
def file_info_save():
    """
    添加文件信息
    :return:
    """
    form = FileInfoForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    file_info_service.save(form)
    return R.success("添加文件信息成功")


@file_info.route("/update", methods=['POST'])
@HasPerm(access="sys:fileInfo:update", name="修改文件信息")
def file_info_update():
    """
    修改文件信息
    :return:
    """
    form = FileInfoForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    file_info_service.update(form)
    return R.success("修改文件信息成功")


@file_info.route("/remove", methods=['POST'])
@HasPerm(access="sys:fileInfo:remove", name="删除文件信息")
def file_info_remove():
    """
    删除文件信息
    :return:
    """
    form = IdsForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    file_info_service.remove(form)
    return R.success("删除文件信息成功")


@file_info.route("/upload", methods=['POST'])
@HasPerm(name="文件上传")
def file_info_upload():
    """
    上传文件，成功返回文件 id/url
    :return:
    """
    # 获取上传的文件
    file = request.files.get('file')
    if not file:
        return R.fail("文件不能为空")
    # 获取参数
    object_type = request.form.get('objectType', 'default')
    persist = int(request.form.get('persist', 1))
    # 声明文件上传服务
    file_upload_service = current_app.config["file_upload_service"]
    # 使用新的文件上传服务上传文件
    result = file_upload_service.upload_file(file, file.filename, object_type)
    # 构建文件信息对象
    file_info_dict = {
        'id': generate_id(),
        'url': result["url"],
        'size': result["size"],
        "sizeInfo": result["size_info"],
        'filename': result["filename"],
        'originalFilename': result["original_filename"],
        'ext': result["ext"],
        'path': result["path"],
        'platform': result["platform"],
        "contentType": result["content_type"],
        'objectId': str(generate_id()),
        'objectType': object_type,
        'attr': f'{{"persist": {persist}, "ext": "{result["ext"]}"}}'
    }
    # 如果需要持久化，则保存到数据库
    if persist == 1:
        file_info_model = FileInfo(**file_info_dict)
        file_info_model.id = file_info_dict['id']
        db.session.add(file_info_model)
        db.session.commit()
    # 返回结果
    result_data = {
        'fullUrl': UrlWrapUtil.wrap(result["url"]),
        'url': result["url"],
        'fileInfoId': str(file_info_dict['id'])
    }
    return R.data(result_data)
